package tk.xboot.boot.web;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

@Controller
public class I18nController {
    @GetMapping("i18n")
    public String getI18nPage() {
        return "i18n";
    }


    /**
     * 最核心的部分就是如何设置会话的区域，也就是如下代码：
     * request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME,new Locale("en","US"));
     * 这个代码就可以把当前会话的区域进行切换,但是不能切换cookie
     *
     * @param request
     * @param lang
     * @return
     */
    @RequestMapping("changeSessionLanauage")
    public String changeSessionLanauage(HttpServletRequest request, String lang) {

        System.out.println(lang);

        if ("zh".equals(lang)) {
            //代码中即可通过以下方法进行语言设置
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("zh", "CN"));
        } else if ("en".equals(lang)) {
            //代码中即可通过以下方法进行语言设置
            request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, new Locale("en", "US"));
        }
        return "redirect:/hello";
    }


    /**
     * 使用:LocaleResolverlocaleResolver = RequestContextUtils.getLocaleResolver(request);
     * 获取当前使用的区域解析器LocaleResolver 调用里面的方法
     * setLocale设置即可，这样的代码就是不管是会话还是cookie区域解析器都是一样的代码
     *
     * @param request
     * @param response
     * @param lang
     * @return
     * @see tk.xboot.boot.web.I18nConf#localeResolver 和
     * @see tk.xboot.boot.web.LocaleChangeInterceptor 来完成语言的切换
     * 功能
     */
    @RequestMapping("changeSessionLanauage_X")
    public String changeSessionLanauage_X(HttpServletRequest request, HttpServletResponse response, String lang) {
        System.out.println(lang);
        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if ("zh".equals(lang)) {
            localeResolver.setLocale(request, response, new Locale("zh", "CN"));
        } else if ("en".equals(lang)) {
            localeResolver.setLocale(request, response, new Locale("en", "US"));
        }
        return "redirect:/";
    }
}
